package com.cjfan.trendplus.noteit.add;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.cjfan.trendplus.noteit.NoteIT;
import com.cjfan.trendplus.noteit.R;
import com.cjfan.trendplus.noteit.wordbank.WordbankActivity;
import com.cjfan.trendplus.sqlit.DatabaseHandler;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaPlayer.OnCompletionListener;

@SuppressLint({ "NewApi", "NewApi" })
public class AddNewItemActivity extends Activity{
	private DatabaseHandler db=null;
	Button homeBtn,backBtn,chineseBtn,englishBtn,recordBtn,sanpshotBtn,locationBtn,saveBtn;
	TextView showChinese, showEnglish;
	String chinese, english, imageBase64;
	ImageView image;
	Bitmap bmp = null;
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
	
	private Uri fileUri;
	ImageView imageView;
	Camera myCamera;// Camera的引用
    boolean isView = false;// 是否在瀏覽中
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;
	private File recPATH;
	Cursor cursor;
	
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        recPATH=Environment.getExternalStorageDirectory(); //SD卡路徑
        //檢查是否存在NoteIT資料夾
    	String path = recPATH.getPath()+"/NoteIT"; 
    	recPATH = new File(path); 
        if(!recPATH.exists()) {
        	recPATH.mkdir();
        }
        
        setContentView(R.layout.activity_add_new);
        this.imageView = (ImageView) this.findViewById(R.id.img);
        homeBtn = (Button)findViewById(R.id.homeBtn);
        backBtn = (Button)findViewById(R.id.backBtn);
        chineseBtn = (Button)findViewById(R.id.chineseBtn);
        englishBtn = (Button)findViewById(R.id.EnglishBtn);
        recordBtn = (Button)findViewById(R.id.recordBtn);
        sanpshotBtn = (Button)findViewById(R.id.snapshotBtn);
        locationBtn = (Button)findViewById(R.id.locationBtn);
        saveBtn = (Button)findViewById(R.id.saveBtn);
        
        homeBtn.setOnClickListener(btnTrigger);
        backBtn.setOnClickListener(btnTrigger);
        recordBtn.setOnClickListener(btnTrigger);
        saveBtn.setOnClickListener(btnTrigger);
        chineseBtn.setOnClickListener(alertBtnClickListener);
        englishBtn.setOnClickListener(alertBtnClickListener);
        sanpshotBtn.setOnClickListener(alertBtnClickListener);
        
        db =new DatabaseHandler(this);// 建立 MyDB 物件
        db.open();  
        cursor=db.getAll();// 載入全部資料
    }
	
	private OnClickListener btnTrigger=new OnClickListener(){
		@Override
		public void onClick(View v) {
			switch(v.getId()){
				case R.id.homeBtn:
				{
					Intent intentHome = new Intent();
					intentHome.setClass(AddNewItemActivity.this, NoteIT.class);
			    	startActivity(intentHome);
			    	AddNewItemActivity.this.finish();
				  	break;
				}
				case R.id.backBtn:
				{
					Intent intentBack = new Intent();
					intentBack.setClass(AddNewItemActivity.this, NoteIT.class);
			    	startActivity(intentBack);
			    	AddNewItemActivity.this.finish();
					break;
				}
				case R.id.recordBtn:
				{
					Intent intentRec = new Intent();
					intentRec.setClass(AddNewItemActivity.this, RecordActivity.class);
			    	startActivity(intentRec);
			    	AddNewItemActivity.this.finish();
					break;
				}
				case R.id.saveBtn:
				{
					try {
						//save data
						chinese = showChinese.getText().toString();
						english = showEnglish.getText().toString();
						imageBase64 = saveImage();
						if (db.append(chinese,english,imageBase64)>0){
						    cursor=db.getAll();// 載入全部資料
						}
						Toast.makeText(AddNewItemActivity.this,"存檔成功",Toast.LENGTH_LONG).show();
						//turn to wordbank 
						Intent intentWB = new Intent();
						intentWB.setClass(AddNewItemActivity.this, WordbankActivity.class);
				    	startActivity(intentWB);
				    	AddNewItemActivity.this.finish();
						
					} catch (Exception e1) {
						Toast.makeText(AddNewItemActivity.this,"存檔前，中文或英文意義不得空白",Toast.LENGTH_LONG).show();
						e1.printStackTrace();
					}
			        
			       
      			    break;
				}
				default:
			}
		}
    };
    public String saveImage(){
    	image = (ImageView) findViewById(R.id.img);
		//imageView轉Bitmap
        //imageView_save.setDrawingCacheEnabled(true);
        //建立圖片的緩存，圖片的緩存本身就是一個Bitmap
        image.buildDrawingCache();
        //取得緩存圖片的Bitmap檔
        Bitmap bmp=image.getDrawingCache();
        //轉換為圖片指定大小
        //獲得圖片的寬高
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        // 設置想要的大小
        int newWidth = 480;
        int newHeight = 525;
        // 計算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix參數
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的圖片
        Bitmap newbm = Bitmap.createBitmap(bmp, 0, 0, width, height, matrix,true);
       
        // 先把 bitmap 轉成 byte
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        newbm.compress(Bitmap.CompressFormat.JPEG, 100, stream );
        byte bytes[] = stream.toByteArray();
        // Android 2.2以上才有內建Base64，其他要自已找Libary或是用Blob存入SQLite
        // 把byte變成base64
        String base64 = Base64.encodeToString(bytes, Base64.DEFAULT); 
        
    	return base64;
    }
    
    private OnClickListener alertBtnClickListener = new OnClickListener(){
  	  @Override
  	  public void onClick(View v) {
  		  AlertDialog.Builder dialog = new AlertDialog.Builder(AddNewItemActivity.this);
  		  switch(v.getId()){
  		  	  case R.id.chineseBtn:
  		  	  {
  		  		dialog.setTitle("選擇輸入方式");		  	    
	  		    dialog.setPositiveButton("語音輸入", new DialogInterface.OnClickListener() {
			  	    // do something when the button is clicked
				  	public void onClick(DialogInterface arg0, int arg1) {
			  	    	
				  	}
	  		  	});
	  			dialog.setNegativeButton("鍵盤輸入", new DialogInterface.OnClickListener() {
	  				AlertDialog.Builder dialogKeyin = new AlertDialog.Builder(AddNewItemActivity.this);
			  	     // do something when the button is clicked
	  		  		 public void onClick(DialogInterface arg0, int arg1) {
	  		  			dialogKeyin.setTitle("輸入中文意思");
			  		  	final EditText editChineseText = new EditText(AddNewItemActivity.this);
			  		    
			  		    editChineseText.setHint("請輸入中文意思");
			  		    dialogKeyin.setView(editChineseText);
				  	    
			  		  	dialogKeyin.setPositiveButton("確認", new DialogInterface.OnClickListener() {
					  	    // do something when the button is clicked
						  	public void onClick(DialogInterface arg0, int arg1) {
					  	    	chinese = editChineseText.getText().toString();
					  	    	showChinese = (TextView)findViewById(R.id.chineseTV);
					  	    	showChinese.setText(chinese);
						  	}
			  		  	});
			  			dialogKeyin.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					  	     // do something when the button is clicked
			  		  		 public void onClick(DialogInterface arg0, int arg1) {
					  	     //...
					  	     }
			  		  	});
			  			dialogKeyin.show();
			  	     }
	  		  	});
	  			dialog.show();
  		  	  } 	
		  	  break;
	  		  	
  		  	  case R.id.EnglishBtn:
	  		  {
	  		  		dialog.setTitle("選擇輸入方式");		  		 			  	    
		  		    dialog.setPositiveButton("語音輸入", new DialogInterface.OnClickListener() {
				  	    // do something when the button is clicked
					  	public void onClick(DialogInterface arg0, int arg1) {
				  	    	
					  	}
		  		  	});
		  			dialog.setNegativeButton("鍵盤輸入", new DialogInterface.OnClickListener() {
		  				AlertDialog.Builder dialogKeyin = new AlertDialog.Builder(AddNewItemActivity.this);
				  	     // do something when the button is clicked
		  		  		 public void onClick(DialogInterface arg0, int arg1) {
		  		  			dialogKeyin.setTitle("輸入英語意思");
				  		  	final EditText editEnglishText = new EditText(AddNewItemActivity.this);
				  		    
				  		    editEnglishText.setHint("請輸入英語意思");
				  		    dialogKeyin.setView(editEnglishText);
					  	    
				  		  	dialogKeyin.setPositiveButton("確認", new DialogInterface.OnClickListener() {
						  	// do something when the button is clicked
							  	public void onClick(DialogInterface arg0, int arg1) {
						  	    	english = editEnglishText.getText().toString();
						  	    	showEnglish = (TextView)findViewById(R.id.Engish);
						  	    	showEnglish.setText(english);
							  	}
				  		  	});
				  			dialogKeyin.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						  	     // do something when the button is clicked
				  		  		 public void onClick(DialogInterface arg0, int arg1) {
						  	     //...
						  	     }
				  		  	});
				  			dialogKeyin.show();
				  	     }
		  		  	});
		  			dialog.show();
	  		  	 } 	
	    		  	break;
	    		
  		  	  case R.id.snapshotBtn:
	  		  		// create Intent to take a picture and return control to the calling application
	  		  	    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	  		  	    
	  		  	    fileUri = getOutputMediaFileUri(1); // create a file to save the image
	  		  	    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
	  		  	    
	  		  	    // start the image capture Intent
	  		  	    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
	  		  		
	  		  	    break;
	  		  	    
  		  }
  	  }
    };
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       try {
           if (requestCode != 0) {
              return;
           }
           super.onActivityResult(requestCode, resultCode, data);

           if (data != null) {
              Bundle extras = data.getExtras();
              bmp = (Bitmap)extras.get("data");            
           }else {
              FileInputStream fis = new FileInputStream(fileUri.getPath());
              bmp = BitmapFactory.decodeStream(fis);
           }
           image = (ImageView)findViewById(R.id.img);
           image.setImageBitmap(bmp);

       } catch (Exception e){
           System.out.println(e.getMessage());
       }
    }
    
    /** Create a file Uri for saving an image or video */
    private static Uri getOutputMediaFileUri(int type){
          return Uri.fromFile(getOutputMediaFile(type));
    }
    
    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                  Environment.DIRECTORY_PICTURES), "MyCameraApp");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE){
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
            "IMG_"+ timeStamp + ".jpg");
        } else if(type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
            "VID_"+ timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }

}
